package com.yihaodian.search.broker.shard;

import java.util.HashMap;
import java.util.Map;

import com.yihaodian.api.client.HedwigServiceProvider;
import com.yihaodian.api.search.SearchException;
import com.yihaodian.api.search.SearchResponse;
import com.yihaodian.api.search.SugRequest;
import com.yihaodian.api.search.SugResponse;

/**
 * request --> one node in given node set. <br>
 * we leverage hedwig to pick up node and remote invoke.
 * 
 */
public class ShardSearchClient implements ShardSearchService {
	static long timeout = 500000;
	static long readTimeout = 200000;

	/**
	 * <shardId, shard service proxy>, here hedwig proxy means a list of nodes
	 * serving the shard.
	 */
	Map<String, ShardSearchService> shardSearchServices = new HashMap<String, ShardSearchService>();

	public ShardSearchClient() {

	}

	/**
	 * 
	 * @param shard
	 * @return
	 */
	ShardSearchService shardSearchService(String shard) {
		ShardSearchService service = shardSearchServices.get(shard);

		if (service == null) {
			synchronized (this) {
				service = shardSearchServices.get(shard);

				if (service == null) {
					service = HedwigServiceProvider.getProxy(
							HedwigServiceProvider.serviceName_shardSearch,
							shard, ShardSearchService.class, timeout,
							readTimeout, null, 0);
					shardSearchServices.put(shard, service);
				}
			}
		}

		return service;
	}

	ShardSearchService shardSearchService(String indexName, String shardId) {
		String shard = HedwigServiceProvider.shardServiceVersion(indexName,
				shardId);
		ShardSearchService service = shardSearchService(shard);

		return service;
	}

	@Override
	public ShardSearchResponse executeSearch(ShardSearchRequest request)
			throws SearchException {
		ShardSearchService service = shardSearchService(request
				.getSearchRequest().getIndexName(), request.getShardId());

		return service.executeSearch(request);
	}

	@Override
	public SugResponse executeSug(String indexName, String shardId,
			SugRequest request) throws SearchException {
		ShardSearchService service = shardSearchService(indexName, shardId);

		return service.executeSug(indexName, shardId, request);
	}

	// @Override
	// public QuerySearchResult executeQueryPhrase(ShardSearchRequest request)
	// throws SearchException {
	// ShardSearchService service = shardSearchService(request);
	//
	// return service.executeQueryPhrase(request);
	// }
	//
	// @Override
	// public FetchSearchResult executeFetchPhrase(FetchRequest request)
	// throws SearchException {
	// // TODO FetchRequest need contains Shard
	// ShardSearchService service = shardSearchService(request.request);
	//
	// return service.executeFetchPhrase(request);
	// }
}
